import { constantRoutes, superRoutes, noRoleRouters, emptyHomeRouters } from '@/router'
import { getMenus } from '@/svc/account'
import Layout from '@/views/layout'
import NestedLayout from '@/views/layout/NestedLayout'
const _import = require('@/router/importer/_import_' + process.env.NODE_ENV)

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

const state = {
  routes: [],
  homePage: null,
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  },
  SET_HOME: (state, home) => {
    // console.log('home - set', home)
    state.homePage = home
  }
}

const homePath = '/dashboard'

/**
 * isMenuExists 判断菜单是否在树中存在，
 * 根据 path 属性
 * @param {*} menuAry 菜单树
 * @param {*} menu 要查找的菜单
 */
function isMenuExists(menuAry, menu) {
  if (!menuAry) return false
  for (let n = 0; n < menuAry.length; n++) {
    if (menuAry[n].path === menu.path) {
      return true
    }
    if (isMenuExists(menuAry[n].children, menu)) {
      return true
    }
  }
  return false
}

function localizeMenus(menuAry, top) {
  const menus = []
  // console.log('localizeMenus', menuAry)
  if (menuAry) {
    const reg = new RegExp('_', 'g')
    for (let n = 0; n < menuAry.length; n++) {
      const item = menuAry[n]
      item['name'] = item['name'].replace(reg, '')
      let children = null
      if (item['children']) {
        children = localizeMenus(item['children'], false)
      }
      if (top) {
        // 顶级菜单
        if (item['component'] !== 'Layout') {
          try {
            // 不是 Layout
            const comp = _import(item['component'])
            comp.name = item['name']
            const page = {
              path: item['path'],
              name: item['name'],
              redirect: item['redirect'],
              component: comp,
              meta: item['meta']
            }
            const lst = [page]
            if (children && children.length > 0) {
              // 增加平行隐藏节点，用来放子节点
              lst.push({
                path: page['path'] + '/container',
                // path: child['path'] === '/dashboard' ? '/' : (child['path'] + '/container'),
                redirect: page['path'],
                hidden: true,
                component: NestedLayout,
                meta: item['meta'],
                children: children
              })
            }
            // 根节点添加容器节点
            menus.push({
              path: page['path'] === homePath ? '/' : (page['path'] + '/container'), // item['path'] + '/container',
              redirect: page['path'] === homePath ? page['path'] : page['redirect'],
              // path: item['path'] + '/container',
              component: Layout,
              children: lst
            })
          } catch {
            console.log('1 找不到组件', item['component'])
          }
        } else {
          // 是 Layout
          const page = {
            path: item['path'],
            redirect: item['redirect'],
            component: Layout,
            meta: item['meta'],
            children: children
          }
          if (children) {
            page['children'] = children
          }
          menus.push(page)
        }
      } else {
        // 非顶级菜单
        if (item['component'] !== 'Layout') {
          // 不是 Layout
          try {
            const comp = _import(item['component'])
            comp.name = item['name']
            const page = {
              path: item['path'] === homePath ? '/' : item['path'],
              name: item['name'],
              // redirect: item['redirect'],
              component: comp,
              meta: item['meta']
            }
            // const lst = [page]
            if (children && children.length > 0) {
              // 增加平行隐藏节点，用来放子节点
              menus.push({
                path: page['path'] + '/container',
                // path: child['path'] === '/dashboard' ? '/' : (child['path'] + '/container'),
                redirect: page['path'],
                hidden: true,
                component: NestedLayout,
                meta: item['meta'],
                children: children
              })
            }
            menus.push(page)
          } catch {
            console.log('2 找不到组件', item['component'])
          }
        } else {
          // 是 Layout
          const page = {
            path: item['path'],
            redirect: item['redirect'],
            component: NestedLayout,
            meta: item['meta'],
            children: children
          }
          if (children) {
            page['children'] = children
          }
          menus.push(page)
        }
      }
    }
  }
  return menus
}

// function localizeMenus(menuAry, top) {
//   const menus = []
//   if (menuAry) {
//     for (let n = 0; n < menuAry.length; n++) {
//       const item = menuAry[n]
//       let children = null
//       if (item['children']) {
//         children = localizeMenus(item['children'], false)
//       }
//       if (top && item['component'] !== 'Layout') {
//         // 顶级菜单，且不是 Layout 组件
//         const child = {
//           // path: '/' + item['path'],
//           path: item['path'],
//           name: item['name'],
//           redirect: item['redirect'],
//           component: _import(item['component']),
//           meta: item['meta']
//           // children: children
//         }
//         const lst = [child]
//         if (children && children.length > 0) {
//           lst.push({
//             path: child['path'] + '/container',
//             // path: child['path'] === '/dashboard' ? '/' : (child['path'] + '/container'),
//             redirect: child['path'],
//             hidden: true,
//             component: NestedLayout,
//             meta: item['meta'],
//             children: children
//           })
//         }
//         menus.push({
//           path: item['path'] + '/container',
//           // path: '/' + item['path'] + '/container',
//           component: Layout,
//           children: lst
//         })
//         // if (!children) {
//         //   delete child['children']
//         // }
//         // console.log('top no layout', child)
//       } else {
//         let child = {}
//         if (item['component'] === 'Layout') {
//           child = {
//             // path: (top ? '/' : '') + item['path'],
//             // path: '',
//             // path: '', // item['path'] + '/container',
//             path: item['path'] + '/container',
//             redirect: item['redirect'],
//             component: top ? Layout : NestedLayout,
//             meta: item['meta'],
//             children: children
//           }
//           if (!children) {
//             delete child['children']
//           }
//           menus.push(child)
//         } else { // 非 Layout
//           // let containerLayout
//           // if (top) {

//           // } else {

//           // }
//           child = {
//             path: item['path'],
//             // path: '/' + item['path'],
//             // path: (top ? '/' : '') + item['path'],
//             name: item['name'],
//             component: _import(item['component']),
//             meta: item['meta']
//             // children: children
//           }
//           // 添加路由
//           menus.push(child)
//           if (children && children.length > 0) {
//             // children.forEach(item => {
//             //   item['path'] = '/' + item['path']
//             // })
//             // 添加隐藏路由
//             menus.push({
//               // path: '/' + item['path'] + '/container',
//               path: item['path'] + '/container',
//               redirect: child['path'],
//               hidden: true,
//               component: NestedLayout,
//               meta: item['meta'],
//               children: children
//             })
//           }

//           // console.log('comp', _import(item['component']))
//         }
//       }
//     }
//   }
//   return menus
// }

const actions = {
  getHomePage({ state }) {
    return state.homePage
  },
  generateRoutes({ commit, rootState }, roles) {
    return new Promise(resolve => {
      // 获取动态菜单
      getMenus().then(res => {
        // console.log(res)
        let home = res['data']['home']
        const dynamicMenus = localizeMenus(res['data']['menus'], true)
        // console.log('got', dynamicMenus)
        // let accessedRoutes
        // let baseRoutes = asyncRoutes || []
        let baseRoutes = dynamicMenus || []

        // let home = res['data']['home']
        // console.log('home', home)
        if (rootState.user.superRole === 'admin') {
        // if (roles.includes('super') ||
        //   (roles.includes('admin') && process.env.NODE_ENV === 'development')) {
          // 超级用户菜单
          if (home) {
            // 如果已经有 home 页，则把超级用户的 home 页移除
            superRoutes.shift()
          } else {
            // 没有 home 页
            home = superRoutes[0]
          }
          baseRoutes = superRoutes.concat(baseRoutes)
        }
        if ((!home) || !isMenuExists(baseRoutes, home)) {
          // home 页是空的
          if (roles.length === 0 || (roles.length === 1 && roles[0] === '')) {
            // 角色是空的，提示设置角色
            home = noRoleRouters[0]
            baseRoutes = noRoleRouters.concat(baseRoutes)
          } else {
            // 角色不是空的，提示设置角色主页
            home = emptyHomeRouters[0]
            baseRoutes = emptyHomeRouters.concat(baseRoutes)
          }
        }
        // if (roles.length === 0 || (roles.length === 1 && roles[0] === '')) {
        //   home = noRoleRouters[0]
        //   baseRoutes = noRoleRouters.concat(baseRoutes)
        // } else if (!home) { // 没有设置首页
        //   if (roles.includes('super')) {
        //     // 超级管理员首页
        //     home = superRoutes[0]
        //   } else {
        //     home = emptyHomeRouters[0]
        //     baseRoutes = emptyHomeRouters.concat(baseRoutes)
        //   }
        // }

        // console.log('baseRoutes', home)
        const accessedRoutes = baseRoutes
        // baseRoutes = baseRoutes.concat(asyncRoutes)
        // if (roles.includes('admin')) {
        //   accessedRoutes = baseRoutes // asyncRoutes || []
        // } else {
        //   accessedRoutes = filterAsyncRoutes(baseRoutes, roles) // filterAsyncRoutes(asyncRoutes, roles)
        // }
        commit('SET_ROUTES', accessedRoutes)
        commit('SET_HOME', home) // res['data']['home'])
        // console.log('got', dynamicMenus)
        resolve(accessedRoutes)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
